package com.group.util;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.group.controller.BaseController;
import com.group.dao.GeneralBeanDao;
import com.group.model.BackUser;

@Aspect
@Service
public class OperationFilter {

	private static final Logger logger = LoggerFactory.getLogger(OperationFilter.class);

	@Autowired
	BaseController baseController;

	@PostConstruct
	public void post() {
	}

	@Autowired
	GeneralBeanDao beanDao;

	@Pointcut("execution( * com.group.controller.*Controller.*(..))")
	private void privileged() {

	}

	@Before("privileged()")
	public void checkPrivilege(JoinPoint sp) {
		privilegeMethod(sp);
	}

	public void privilegeMethod(JoinPoint sp) {
//		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

		/*String password = request.getParameter("password");
		if (StringUtils.isEmpty(password))
			request.setAttribute("userId", "null");
		else if (password.equals(WeiXinConf.PASSWORD)) {
			request.setAttribute("userId", request.getParameter("userId"));
			request.setAttribute("openid", request.getParameter("openid"));
		}*/

	}

	/**
	 * 验证当前操作是否是超级管理员
	 */
	@Pointcut("execution(@(com.group.interface1.RequireSuperAdmin) * com.group.controller.*.*(..))")
	private void superAdmin() {
	}

	// 验证当前操作是否是超级管理员
	@Before("superAdmin()")
	public void checkSuperAdmin(JoinPoint sp) {
		MethodSignature ms = (MethodSignature) sp.getSignature();
		String methodName = ms.getMethod().getName();

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		BackUser user = baseController.getBackUser(request);

		// 超级管理员
		if (!user.getRole().equals("超级管理员")) {
			throw new NoteException("非超级管理员不能操作");
		}

	}

	/**
	 * 验证分页参数
	 */
	@Pointcut("execution(@(com.group.interface1.ValidPagePara) * com.group.controller.*.*(..))")
	private void validPagePara() {
	}

	@Before("validPagePara()")
	public void validPageParaImpl(JoinPoint sp) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");

		if (start == null || limit == null) {
			throw new NoteException("分页参数不合法");

		}

	}

}
